<?php
$loader->requireOnce('includes/Grid.class.php');
$loader->requireOnce('datasources/User_DS.class.php');
$loader->requireOnce('ordo/Employee.class.php');

/**
 * Controller for the Clearhealth users
 */
class C_User extends Controller {
	const DEFAULT_PROVINCE = 29; // Ho Chi Minh
	const DEFAULT_DISTRICT = 1; // District 1
	
	function C_User ($template_mod = "general") {
		parent::Controller($template_mod);
		$this->assign("TOP_ACTION", Celini::link('list'));
		$this->setLayout('admin');
	}

	/**
	 * Edit/Add a User
	 *
	 */
	function actionEdit($employeeId = 0) {	
	    if (isset($_GET['employeeId'])) {
	        $employeeId = $_GET['employeeId'];
	    }			
		$employeeType = Celini::newORDO('EmployeeType');
		$this->assign('employeeTypeList', $employeeType->listAllParentType());									
		
		$employee = Celini::newORDO('Employee', $employeeId);								
		$user =& User::fromPersonId($employeeId);		
				
		$this->assign("roles", $user->getDisplayGroups('roles'));								
		$this->assign('deptList', Celini::newOrdo('Department')->listAll());
		$this->assign('diplomaList', $employee->getDiplomaList(0, true));	
		$this->assign_by_ref('employee',$employee);
		$this->assign_by_ref('user',$user);
		
		$orders	=	L10nHelper::getYMDorder();
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);
		
		$dateObj = new DateObject();
		$dateObj = $dateObj->create($employee->get('date_of_birth'));
		$dob = array (
				'dd' => $dateObj->getDay(),
				'mm' => $dateObj->getMonth(),
				'yyyy' => $dateObj->getYear()
		);		
	
		$this->assign('dob', $dob);		
		
		return $this->view->render('edit.html');
	}

	/**
	 * List Users
	 */
	function actionList($deptId = 0, $roleGroupId = 0, $status = 'all') {		
	    $this->assign('deptList', Celini::newOrdo('Department')->listAll());	    
	    $this->assign('roleList', Celini::newOrdo('User')->getDisplayGroups('roles'));
	    
		$ds =& new User_DS($deptId, $roleGroupId, $status);						
		$this->view->assign_by_ref('userList',$ds->toArray());
		return $this->view->render("list.html");
	}

	function actionManagement() {
		return $this->view->render("management.html");
	}
	
	function actionFilter($deptId = 0, $roleGroupId = 0, $status = 'all') {
        if (isset($_GET['deptId'])) $deptId = $_GET['deptId'];
        if (isset($_GET['roleGroupId'])) $roleGroupId = $_GET['roleGroupId'];
        if (isset($_GET['status'])) $status = $_GET['status'];
        
        $ds =& new User_DS($deptId, $roleGroupId, $status);						
		$this->view->assign_by_ref('userList',$ds->toArray());
		return $this->view->render("list_body.html");                	        
	}

	/**
	 * ERROR
	 * 		1. Unexpected Error
	 * 		2. Duplicated Username
	 */
	public function actionEditUserAjax() {	  	    	    
	    $employee = $_POST['employee'];
	    $user = $_POST['user'];
	    $user['groups'][] = $user['role'];
	    // Checking before persist - hidden field employeeId 
	    
	    // username and employeeId is not from a user
	    // employeeId > 0 and username is not employeeID

	    $e = Celini::newOrdo('Employee');
	    $u = Celini::newOrdo('User');
	     
	    // Edit an user
	    if ($employee['person_id'] > 0) {
	        $e->setup($employee['person_id']);
	        // EmployeeId is not exist
	        if (!$e->isPopulated()) {
	            return -1;
	        }		             
	    }
	    // Add new username
	    // duplicated username
	    if (isset($user['username'])) {	         
	        $u->setupByUsername($user['username']);
	        if ($u->isPopulated()) {
	            return -2;
	        }	        	        
	    }
        $employee['date_of_birth'] = $employee['dob_yyyy'] . '-' 
		                            . $employee['dob_mm'] . '-'
		                            . $employee['dob_dd']; 
        $employee['mapped'] = 'yes';		                            
	    $e->populateArray($employee);
	    $e->persist();	    
	   
	    $this->processUserACL($e->get('person_id'), $user);	    
	    return $e->get('person_id'); 
	} 	
	
	private function processUserACL($person_id, $data) {
		/* 
		 * If this username is 'admin', attempt to load it and tie this 
		 * new person to it
		 */
		if ($data['username'] == 'admin') {
			$u = User::fromUsername('admin');
		} 
		else {
			$u = User::fromPersonId($person_id);					
		}				
				
		$u->set('person_id',$person_id);	
		$u->populateArray($data);	
		$u->persist();
		$this->controller->user_id = $u->get('id');				
		
		// update gacl groups from type
		if ($data['username'] != 'admin') {
			// Setup user groups
			$groups = array();
			if (isset($data['groups'])) {
				$groups = $data['groups'];
				unset($data['groups']);
			}
														
			$u->groups = array();
			foreach($groups as $id) {
				$u->groups[$id] = array('id'=>$id);
			}						
			$u->persist();
		}		
	}
	
	
	/**
	 * Update the password of the currently logged in user
	 */
	function password_action_edit() {
		$user =& $this->_me->get_user();

		$this->assign_by_ref('user',$user);
		
		return $this->view->render("password.html");
	}

	function password_action_process() {
		$user =& $this->_me->get_user();

		if ($_POST['password']['current_password'] !== $user->get('password')) {
			$this->messages->addMessage('Current Password Incorrect');
			return "";
		}
		$user->set('password',$_POST['password']['password']);
		$user->persist();
	}
	
}
?>
